package com.group.integration.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.group.integration.controller.back.vo.DiscountResultVO;
import com.group.integration.repository.CouponRepository;
import com.group.integration.repository.entity.Coupon;
import com.group.integration.service.DifferentCouponService;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

@Service
@Slf4j
@RequiredArgsConstructor
public class DifferentCouponServiceImpl implements DifferentCouponService {

    private final CouponRepository couponRepository;

    private Map<String, Function<String, List<DiscountResultVO>>> neNameTypeMap = new HashMap<>();

    @Override
    public List<DiscountResultVO> getDifferentCouponByType(String type) throws JsonProcessingException {

        Function<String, List<DiscountResultVO>> result = neNameTypeMap.get(type);
        List<DiscountResultVO> apply = new ArrayList<>();
        if (result != null) {
            apply = result.apply(type);
            log.info("查询结果：{}", new ObjectMapper().writeValueAsString(apply));
        }
        return apply;
    }

    @PostConstruct
    public void dispatcherInit() {

        neNameTypeMap.put("cup", this::discountFive);
        neNameTypeMap.put("pen", this::discountNine);

    }

    private List<DiscountResultVO> discountNine(String type) {

        List<Coupon> coupons = couponRepository.findByType(type);
        List<DiscountResultVO> list = new ArrayList<>();
        if (!coupons.isEmpty()) {
            for (Coupon coupon : coupons) {
                DiscountResultVO resultVO = new DiscountResultVO();
                BeanUtils.copyProperties(coupon, resultVO);
                list.add(resultVO);
            }
        }
        return list;
    }

    private List<DiscountResultVO> discountFive(String type) {

        List<Coupon> coupons = couponRepository.findByType(type);
        return coupons.stream()
                .map(coupon -> {
                    DiscountResultVO resultVO = new DiscountResultVO();
                    BeanUtils.copyProperties(coupon, resultVO);
                    return resultVO;
                })
                .toList();
    }

    @Override
    public Coupon addCoupon(Coupon coupon) {

        return couponRepository.save(coupon);
    }

}
